<?php

namespace api\controller;

use common\controller\VerifyController;
use common\service\TaskUpstreamService;
use think\Request;
use think\Response;

class TaskRelationController extends VerifyController
{

    /**
     * @var TaskUpstreamService
     */
    private TaskUpstreamService $TaskUpstreamService;

    public function __construct()
    {
        parent::__construct();
        $this->TaskUpstreamService = TaskUpstreamService::getInstance();
    }


    /**
     * 查询任务上游或下游任务
     * @param Request $request
     * @return \think\Response
     */
    public function getStepUpDownstreamTaskList(Request $request)
    {
        $param = $request->param();
        $taskId = $param['task_id'] ?? [];
        $type = $param['type'] ?? 'upstream';
        $resData = $this->TaskUpstreamService->getStepUpDownstreamTaskList($taskId, $type);
        return json(success_response('', $resData));
    }


    /**
     * 根据任务id获取上游任务id
     * @param Request $request
     * @return \think\Response
     */
    public function getTaskUpstreamByTaskIds(Request $request)
    {
        $param = $request->param();
        $fields = $param['param']['fields'] ?? ['target_task_id', 'target_task_id'];
        $filter = $param['param']['filter'] ?? [];
        $page = $param['param']['page'] ?? [1, C("database.database_max_select_rows")];
        $projectId = $param['param']['project_id'] ?? 0;
        $resData = $this->TaskUpstreamService->getTaskUpstreamByTaskIds($filter, $fields, $projectId, $page);
        return json(success_response('', $resData));
    }


    /**
     * task_relation表 根据项目id分表
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function fixProjectIdByTaskRelationPartition(Request $request)
    {
        $resData = $this->TaskUpstreamService->fixProjectIdByTaskRelationPartition();
        return json(success_response('', $resData));
    }

    /**
     * 按照项目id填充数据task_relation分表数据
     * @param Request $request
     * @return Response
     */
    public function fixTaskProjectData(Request $request)
    {
        $resData = $this->TaskUpstreamService->fixTaskProjectData();
        return json(success_response('', $resData));
    }

    /**
     * 通过环节查找工单代办上游任务id
     * @param Request $request
     * @return Response
     */
    public function getTaskWorkOrderStepCategoryUpstreamTaskIds(Request $request): Response
    {
        $param = $request->param()['param'];
        $projectId = $param['project_id'] ?? 0;
        $stepCategoryIds = $param['step_category_id'] ?? [];
        $resData = $this->TaskUpstreamService->getTaskWorkOrderStepCategoryUpstreamTaskIds($projectId, $stepCategoryIds);
        return json(success_response('', $resData));
    }
}
